package com.maxd.controller.helpTask;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.*;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.helpTask.*;
import com.maxd.service.userMoney.UserMoneyService;
import com.maxd.utils.AmountCalUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 房
 * \* Date: 2020/5/14
 * \* Time: 9:59
 * \*
 * \
 */
@RestController
@Api(value = "助力活动", tags = {"助力活动"})
@RequestMapping(value = "/helpTask")
public class helpTaskController {

    /** 助力信息 */
    @Autowired
    private HelpTaskService helpTaskService;
    /** 助力详细信息 */
    @Autowired
    private HelpTaskDetailsService helpTaskDetailsService;
    /** 派单信息 */
    @Autowired
    private HelpTakeOrderService helpTakeOrderService;
    /** 接单信息 */
    @Autowired
    private HelpSendOrderService helpSendOrderService;
    /** 接单详细步骤信息 */
    @Autowired
    private HelpSendOrderDetailsService helpSendOrderDetailsService;
    /** 信誉分 */
    @Autowired
    private HelpUserScoreService helpUserScoreService;
    /** 信誉分明细 */
    @Autowired
    private HelpUserScoreDetailsService helpUserScoreDetailsService;
    /** 用户钱包 */
    @Autowired
    private UserMoneyService userMoneyService;
    /** 维权信息 */
    @Autowired
    private HelpMaintainService helpMaintainService;
    /** 维权详细信息 */
    @Autowired
    private HelpMaintainDetailsService helpMaintainDetailsService;
    /** 浏览记录 */
    @Autowired
    private HelpBrowsingHistoryService helpBrowsingHistoryService;
    @Autowired
    private UserRepository userRepository;

    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @RequestMapping(value = "/selectTakeOrderDetails", method = RequestMethod.GET)
    @ApiOperation("管理平台派单任务详细信息")
    @ResponseBody
    public Result selectTakeOrderDetails(Long id)
    {
        HelpTask helpTask = helpTaskService.selectById(id);
        HelpTakeOrder helpTakeOrder = helpTakeOrderService.selectHelpTakeOrderByHelpTaskId(helpTask.getId());
        UserInfo userEntity = userRepository.getUserById(helpTakeOrder.getUserId());
        if(userEntity!=null){
            helpTask.setNickName(userEntity.getNickName());
        }
        return ResultUtil.success(helpTask);
    }

    @RequestMapping(value = "/selectSendOrderByTaskList", method = RequestMethod.GET)
    @ApiOperation("管理平台派单任务接单人列表")
    @ResponseBody
    public Result selectSendOrderByTaskList(Long id,int page,int size )
    {
        Pageable pageable = PageRequest.of(page, size);
        return ResultUtil.success(helpSendOrderService.selectSendOrderByTaskId(pageable, id));
    }

    @RequestMapping(value = "/selectSendOrderDetailsById", method = RequestMethod.GET)
    @ApiOperation("管理平台派单接单人详细信息")
    @ResponseBody
    public Result selectSendOrderDetailsById(Long id)
    {
        List<HelpSendOrderDetails> helpSendOrderDetails = helpSendOrderDetailsService.selectByHelpSendOrderId(id);
        return ResultUtil.success(helpSendOrderDetails);
    }


    @RequestMapping(value = "/saveMyHelpTask", method = RequestMethod.POST)
    @ApiOperation("新建派单")
    @ResponseBody
    public Result addHelpTask(@RequestBody HelpTask helpTask ) {
        Long userId=helpTask.getUserId();
        String helpTaskDetailss=helpTask.getHelpTaskDetailss();
        //计算该派单需要多少钱
        Double money=AmountCalUtils.mul(helpTask.getTaskNum(),helpTask.getTaskOriginalPrice());
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, helpTask.getEndTimes());
        helpTask.setEndTime(sdf.format(cal.getTime()));
        int i = helpTaskService.saveHelpTask(helpTask, helpTaskDetailss, userId, money);
        if(i==0){
            return ResultUtil.error(-100,"账户余额不足，请充值！");
        }else{
            return ResultUtil.success();
        }

    }


    @RequestMapping(value = "/updateHelpTask", method = RequestMethod.POST)
    @ApiOperation("审核派单")
    @ResponseBody
    public Result updateHelpTask(String helpTakeId,Integer state,String content) {
        helpTaskService.updateHelpTask(helpTakeId,state,content);
        return ResultUtil.success();
    }


    @RequestMapping(value = "/selectTakeOrderAuditHelpTask", method = RequestMethod.GET)
    @ApiOperation("查询派单待审核助力活动")
    @ResponseBody
    public Result selectAuditHelpTask(int page, int size,String phone,Integer state)
    {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        Page<HelpTask> list=helpTaskService.selectHelpTaskLists(state,phone,pageable);
        for(HelpTask helpTask:list.getContent()){
            List<HelpTaskDetails> helpTaskDetailsList = helpTaskDetailsService.selectByHelpTaskId(helpTask.getId());
            helpTask.setHelpTaskDetailsList(helpTaskDetailsList);
        }
        return ResultUtil.success(list);
    }

    @RequestMapping(value = "/selectHelpTask", method = RequestMethod.GET)
    @ApiOperation("查询正常列表助力活动")
    @ResponseBody
    @IgnoreSecurity
    public Result selectHelpTask(int page, int size,Integer sort)
    {
        Sort.Order order;
        if(sort!=null && sort!=0){
            if(sort==1){//最多
                order=new Sort.Order(Sort.Direction.DESC, "task_price");
            }else if(sort==2){//最热
                order=new Sort.Order(Sort.Direction.DESC, "end_num");
            }else{//最早
                order=new Sort.Order(Sort.Direction.ASC, "create_time");
            }
        }else{
            order=new Sort.Order(Sort.Direction.DESC, "id");
        }
        Pageable pageable=PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(helpTaskService.selectHelpTaskList(1,pageable));
    }

    @RequestMapping(value = "/selectMyHelpTask", method = RequestMethod.GET)
    @ApiOperation("查询我派发的助力活动")
    @ResponseBody
    public Result selectMyHelpTask( int page, int size,Integer state,Long userId)
    {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        Page<Map<String,Object>> pageList= helpTaskService.selectMyHelpTask(state,userId,pageable);
        return ResultUtil.success(pageList);
    }

    @RequestMapping(value = "/selectParticipationHelpTask", method = RequestMethod.GET)
    @ApiOperation("查询我接单的助力活动")
    @ResponseBody
    public Result selectParticipationHelpTask( int page, int size,Integer state,Long userId)
    {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(helpTaskService.selectParticipationHelpTask(state,userId,pageable));
    }

    @RequestMapping(value = "/selectAuditHelpTask", method = RequestMethod.GET)
    @ApiOperation("查询接单待审核的助力活动")
    @ResponseBody
    public Result selectAuditHelpTask( int page, int size,Integer state,Long userId)
    {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(helpTaskService.selectAuditHelpTask(state,userId,pageable));
    }

    @RequestMapping(value = "/selectSendOrderList", method = RequestMethod.GET)
    @ApiOperation("管理平台查询接单列表")
    @ResponseBody
    public Result selectSendOrderList(int page,int size,String phone,Integer state)
    {
        Pageable pageable = PageRequest.of(page, size);
        return ResultUtil.success(helpSendOrderService.selectSendOrderList(pageable,phone,state));
    }


    @RequestMapping(value = "/selectHelpTaskDetails", method = RequestMethod.GET)
    @ApiOperation("查看助力活动详细界面")
    @ResponseBody
    public Result selectHelpTaskDetails(Long id,Long userId)
    {
        Long helpBrowsingId=helpBrowsingHistoryService.selectHelpBrowsingHistoryByUserId(userId,id);
        //判断是否浏览过这个活动  没有则新建 有则更新浏览时间
        if(helpBrowsingId==null){
            HelpBrowsingHistory helpBrowsingHistory=new HelpBrowsingHistory();
            helpBrowsingHistory.setCreateTime(sdf.format(new Date()));
            helpBrowsingHistory.setHelpTaskId(id);
            helpBrowsingHistory.setUserId(userId);
            helpBrowsingHistoryService.save(helpBrowsingHistory);
        }else{
            helpBrowsingHistoryService.updateCreateTimeByUserId(id,new Date());
        }
        HashMap<String,Object> map=new HashMap<>();
        HelpTask helpTask=helpTaskService.selectById(id);
        List<HelpTaskDetails> list=helpTaskDetailsService.selectByHelpTaskId(id);
        HelpTakeOrder helpTakeOrder=helpTakeOrderService.selectHelpTakeOrderByHelpTaskId(id);
        map.put("helpTask",helpTask);
        map.put("helpTaskDetailsList",list);
        map.put("helpTakeOrder",helpTakeOrder);
        HelpSendOrder helpSendOrder=helpSendOrderService.selectByHelpTaskId(id,userId);
        //判断活动自己是否参与
        if(helpSendOrder==null){
            map.put("flag",1);
        }else{
            List<HelpSendOrderDetails> list1=helpSendOrderDetailsService.selectByHelpSendOrderId(helpSendOrder.getId());
            map.put("flag",helpSendOrder.getState()+2);
            map.put("helpSendOrder",helpSendOrder);
            map.put("HelpSendOrderDetailsList",list1);
         }
        return ResultUtil.success(map);
    }


    @RequestMapping(value = "/saveHelpTask", method = RequestMethod.POST)
    @ApiOperation("参与活动")
    @ResponseBody
    public Result saveHelpSendOrder(@RequestBody HelpSendOrder helpSendOrder) {
        Integer exits=helpSendOrderService.selectCountByHelpTaskIdAndUserId(helpSendOrder.getHelpTaskId(),helpSendOrder.getUserId());
        if(exits!=null){
            return ResultUtil.error(-100,"您已报名，请不要重复点击！");
        }
        HelpTask helpTask=helpTaskService.selectById(helpSendOrder.getHelpTaskId());
        if(helpTask.getTaskNum().compareTo(helpTask.getEndNum())<=0){
            return ResultUtil.error(-100,"报名人数已满！");
        }

        try {
            if(System.currentTimeMillis()>sdf.parse(helpTask.getEndTime()).getTime()){
                return ResultUtil.error(-100,"活动已经过期！");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer num=helpTakeOrderService.selectCountByHelpTaskIdAndUserId(helpSendOrder.getHelpTaskId(),helpSendOrder.getUserId());
        if(num!=null && num>0){
            return ResultUtil.error(-100,"不能参加自己的活动！");
        }
        helpSendOrderService.save(helpSendOrder);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/endHelpSendOrder", method = RequestMethod.POST)
    @ApiOperation("放弃活动")
    @ResponseBody
    public Result endHelpSendOrder(Long helpSendOrderId) {
        helpSendOrderService.endHelpSendOrder(helpSendOrderId);
        return ResultUtil.success();
    }


    @RequestMapping(value = "/saveHelpSendOrderDetails", method = RequestMethod.POST)
    @ApiOperation("提交活动")
    @ResponseBody
    public Result saveHelpSendOrderDetails(@RequestBody String jsonData) {
        JSONObject job = JSONObject.parseObject(jsonData);
        String helpSendOrderDetailss=job.get("helpSendOrderDetailss").toString();
        Long helpSendOrderId=Long.parseLong(job.get("helpSendOrderId").toString());
        Long helpTaskId=Long.parseLong(job.get("helpTaskId").toString());
        String content=job.get("content").toString();

        List<HelpSendOrderDetails> list=JSONArray.parseArray(helpSendOrderDetailss,HelpSendOrderDetails.class);
        /*if(list.size()==0){判断是否有提交内容
            return ResultUtil.error(-100,"请提交内容！");
        }*/
        HelpTask helpTask=helpTaskService.selectById(helpTaskId);
        HelpSendOrder helpSendOrder=helpSendOrderService.selectById(helpSendOrderId);
        //计算时间 从接单开始到任务结束时间
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(helpSendOrder.getCreateTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        cal.add(Calendar.MINUTE,helpTask.getRestrictTime());
        //计算时间是否超时
        if(System.currentTimeMillis()>cal.getTime().getTime()){
            return ResultUtil.error(-100,"活动已经过期！");
        }
        helpSendOrder.setContent(content);
        helpSendOrderDetailsService.saveAll(list,helpTask,helpSendOrder);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/auditHelpTask", method = RequestMethod.POST)
    @ApiOperation("审核接单")
    @ResponseBody
    public Result auditHelpTask(@RequestBody HelpSendOrder helpSendOrder) {
        HelpSendOrder oldHelpSendOrder=helpSendOrderService.selectById(helpSendOrder.getId());
        if(oldHelpSendOrder.getState()!=1){
            return ResultUtil.error(-100,"派单已经审核过了！");
        }
        helpSendOrderService.updateHelpSendOrder(helpSendOrder,oldHelpSendOrder);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/selectUserScore", method = RequestMethod.GET)
    @ApiOperation("助力活动信誉分查询")
    @ResponseBody
    public Result selectUserScore(Long userId)
    {
        return ResultUtil.success(helpUserScoreService.selectByUserId(userId));
    }

    @RequestMapping(value = "/selectUserScoreDetails", method = RequestMethod.GET)
    @ApiOperation("助力活动信誉分明细查询")
    @ResponseBody
    public Result selectUserScoreDetails(int page,int size,Long userId)
    {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(helpUserScoreDetailsService.selectHelpUserScoreDetailsList(userId,pageable));
    }

    /*@RequestMapping(value = "/saveHelpMaintain", method = RequestMethod.POST)
    @ApiOperation("申请维权")
    @ResponseBody
    public Result saveHelpMaintain(Long helpTaskId,Long sendOrderUserId,String content,String picture) {
        HelpMaintain helpMaintain=new HelpMaintain();
        helpMaintain.setHelpTaskId(helpTaskId);
        helpMaintain.setSendOrderUserId(sendOrderUserId);
        HelpMaintainDetails helpMaintainDetails=new HelpMaintainDetails();
        helpMaintainDetails.setContent(content);
        helpMaintainDetails.setPicture(picture);
        HelpSendOrder helpSendOrder=helpSendOrderService.selectByHelpTaskId(helpMaintain.getHelpTaskId(),helpMaintain.getSendOrderUserId());
        if(helpSendOrder.getState()!=3){
            return ResultUtil.error(-100,"当前状态不可以维权！");
        }
        HelpTask helpTask=helpTaskService.selectById(helpMaintain.getHelpTaskId());
        if(helpTask.getState()==4){
            return ResultUtil.error(-100,"活动已经结束！");
        }
        HelpTakeOrder helpTakeOrder=helpTakeOrderService.selectHelpTakeOrderByHelpTaskId(helpMaintain.getHelpTaskId());
        if(helpTakeOrder==null){
            return ResultUtil.error(-100,"活动已经结束！");
        }
        helpMaintain.setHelpTakeOrderId(helpTakeOrder.getId());
        helpMaintain.setHelpSendOrderId(helpSendOrder.getId());
        helpMaintain.setTakeOrderUserId(helpTakeOrder.getUserId());
        helpMaintainService.insert(helpMaintain,helpMaintainDetails,helpSendOrder);
        return ResultUtil.success();
    }*/

    @RequestMapping(value = "/saveHelpMaintain", method = RequestMethod.POST)
    @ApiOperation("申请维权")
    @ResponseBody
    public Result saveHelpMaintain(Long helpTaskId,Long sendOrderUserId) {
        HelpMaintain helpMaintain=new HelpMaintain();
        helpMaintain.setHelpTaskId(helpTaskId);
        helpMaintain.setSendOrderUserId(sendOrderUserId);
        HelpSendOrder helpSendOrder=helpSendOrderService.selectByHelpTaskId(helpMaintain.getHelpTaskId(),helpMaintain.getSendOrderUserId());
        if(helpSendOrder.getState()!=3){
            return ResultUtil.error(-100,"当前状态不可以维权！");
        }
        HelpTask helpTask=helpTaskService.selectById(helpMaintain.getHelpTaskId());
        if(helpTask.getState()==4){
            return ResultUtil.error(-100,"活动已经结束！");
        }
        HelpTakeOrder helpTakeOrder=helpTakeOrderService.selectHelpTakeOrderByHelpTaskId(helpMaintain.getHelpTaskId());
        if(helpTakeOrder==null){
            return ResultUtil.error(-100,"活动已经结束！");
        }
        helpMaintain.setHelpTakeOrderId(helpTakeOrder.getId());
        helpMaintain.setHelpSendOrderId(helpSendOrder.getId());
        helpMaintain.setTakeOrderUserId(helpTakeOrder.getUserId());
        helpMaintainService.insert(helpMaintain,helpSendOrder);
        return ResultUtil.success();
    }



    @RequestMapping(value = "/auditHelpMaintain", method = RequestMethod.POST)
    @ApiOperation("审核维权")
    @ResponseBody
    public Result auditHelpMaintain( Long helpMaintainId,Integer state,String content) {
        helpMaintainService.auditHelpMaintain(helpMaintainId,state,content);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/selectAuditHelpMaintainList", method = RequestMethod.GET)
    @ApiOperation("平台审核维权列表")
    @ResponseBody
    public Result selectAuditHelpMaintainList(int page,int size)
    {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        Page<HelpMaintainModel> map=helpMaintainService.selectHelpMaintainList(pageable);
        List<HelpMaintainModel> list=map.getContent();
        for(HelpMaintainModel helpMaintainModel:list){
            Long helpMaintainId=helpMaintainModel.getId();
            List<HelpMaintainDetails> helpMaintainDetailsList= helpMaintainDetailsService.selectByHelpMaintainId(helpMaintainId);
            for(HelpMaintainDetails helpMaintainDetails:helpMaintainDetailsList){
                if(helpMaintainDetails.getClassify()==1){
                    helpMaintainDetails.setHelpTaskDetailsList(helpTaskDetailsService.selectByHelpTaskId(helpMaintainModel.getHelpTaskId()));
                }else{
                    helpMaintainDetails.setHelpSendOrderDetailsList(helpSendOrderDetailsService.selectByHelpSendOrderId(helpMaintainModel.getHelpSendOrderId()));
                }
            }
            helpMaintainModel.setHelpMaintainDetailsList(helpMaintainDetailsList);
        }
        return ResultUtil.success(map);
    }


    @RequestMapping(value = "/selectHelpMaintainListBySendOrder", method = RequestMethod.GET)
    @ApiOperation("接单维权列表")
    @ResponseBody
    public Result selectHelpMaintainListBySendOrder(int page,int size,Long userId,Integer state)
    {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(helpMaintainService.selectHelpMaintainListBySendOrder(userId,state,pageable));
    }


    @RequestMapping(value = "/selectHelpMaintainListByTakeOrder", method = RequestMethod.GET)
    @ApiOperation("派单维权列表")
    @ResponseBody
    public Result selectHelpMaintainListByTakeOrder(int page,int size,Long userId,Integer state)
    {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(helpMaintainService.selectHelpMaintainListByTakeOrder(userId,state,pageable));
    }

    @RequestMapping(value = "/selectHelpMaintainDetails", method = RequestMethod.GET)
    @ApiOperation("维权详细信息")
    @ResponseBody
    public Result selectHelpMaintainDetails(Long helpMaintainId)
    {
        HashMap<String,Object> map=new HashMap<String,Object>();
        HelpMaintain helpMaintain=helpMaintainService.selectById(helpMaintainId);
        List<HelpMaintainDetails> helpMaintainDetailsList= helpMaintainDetailsService.selectByHelpMaintainId(helpMaintainId);
        map.put("helpMaintain",helpMaintain);
        map.put("helpMaintainDetailsList",helpMaintainDetailsList);
        return ResultUtil.success(map);
    }


    @RequestMapping(value = "/finishHelpTask", method = RequestMethod.POST)
    @ApiOperation("结算")
    @ResponseBody
    public Result finishHelpTask(Long helpTaskId) {
        HelpTask helpTask=helpTaskService.selectById(helpTaskId);
        if(helpTask.getState()!=2){
            return ResultUtil.error(-100,"活动没有结束不可以结算！");
        }
        Integer count=helpMaintainService.selectCount(helpTaskId,0);
        if(count!=null && count>0){
            return ResultUtil.error(-100,"活动有维权没有处理完，请处理完后再进行结算！");
        }
        helpTaskService.finishHelpTask(helpTask);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/selectHelpBrowsingHistoryList", method = RequestMethod.GET)
    @ApiOperation("查询浏览记录")
    @ResponseBody
    public Result selectHelpBrowsingHistoryList(Long userId,int page,int size)
    {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "create_time");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(helpBrowsingHistoryService.selectHelpBrowsingHistoryList(userId,pageable));
    }


}